﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DBService;
using System.Windows.Forms;
using DBService.ViewDatas;
using System.Text;

public partial class SingleCompany : System.Web.UI.Page, ICallbackEventHandler
{
    int CompanyID;
    string callBackData = String.Empty;
    int UserID;
    int PageSize = 10;
    int ItemCount;
    int PagesCount;
    string DeleteReviewAdmin = "<a name=\"DeleteReviewAdmin\" class=\"red_x\" href=\"#\"></a>";
    ModelAdapter ma = new ModelAdapter();
    List<UserReviewInfo> _UserReviewInfo = new List<UserReviewInfo>();
    Company Comp;

    public int CurrentPage
    {
        get
        {
            object s1 = this.ViewState["CurrentPage"];
            if (s1 == null)
            {
                return 0;
            }
            else
            {
                return Convert.ToInt32(s1);
            }
        }
        set
        {
            if (value > PagesCount - 1)
            {
                value = PagesCount - 1;
            }
            this.ViewState["CurrentPage"] = value;
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (int.TryParse((string)Request.QueryString["id"], out CompanyID))
        {
            string id, title, descr, url, images;
            Comp = ma.GetCompanies(CompanyID).Single();

            title = CompanyName.InnerText = Comp.Name;
            descr = "Revio.ge"; //- შემოდი, მოძებნე, შეაფასე და მოიგე!";
            url = "http://revio.ge/singlecompany.aspx?id=" + CompanyID;
            id = CompanyID.ToString();

            #region Set Company Categories
            CateoriesList.InnerText = "";
            foreach (var ct in Comp.CompanyCategories)
            {
                CateoriesList.InnerText += ct.Category.Title + ", ";
            }
            if (!String.IsNullOrEmpty(CateoriesList.InnerText) && CateoriesList.InnerText.EndsWith(", "))
            {
                CateoriesList.InnerText = CateoriesList.InnerText.Substring(0, CateoriesList.InnerText.LastIndexOf(","));
            }
            #endregion

            #region set company addressed and phones from company_options
            StringBuilder adrsSB = new StringBuilder();
            var optionsSet = ma.GetCompanyOptions(CompanyID);
            var oss = optionsSet.Where(os => os.OptionTypeID == (int)CompanyOptionType.ADDRESS_PHONE)
                .OrderBy(os => os.SortIndex)
                .ToList();
            if (oss.Count == 0)
            {
                litAddressOptions.Text = String.Format(
                            @"<span>მისამართი:</span> <span class='catg_list_grey'>{0}</span><br />
                        <span>ტელეფონი:</span> <span class='catg_list_grey'>{1}</span><br />"
                        , Comp.Address, Comp.Phone);
            }
            else
            {
                oss.ForEach(os =>
                     adrsSB.Append(String.Format(
                         @"<span>მისამართი:</span> <span class='catg_list_grey'>{0}</span><br />
                        <span>ტელეფონი:</span> <span class='catg_list_grey'>{1}</span><br />"
                     , os.OptionName, os.Value))
                 );
                litAddressOptions.Text = adrsSB.ToString();
            }
            #endregion


            CompanyWebsite.HRef = Comp.Website.StartsWith("http") == true ? Comp.Website : "http://" + Comp.Website;
            CompanyWebsite.InnerText = Comp.Website;
            ReviewsCount.Text = (Comp.Reviews != null ? Comp.Reviews.Where(r => r.IsDeleted == null).Count() : 0).ToString();

            rateing.Style.Add(HtmlTextWriterStyle.Width, ((int)((Comp.Rating ?? 0) * 20)).ToString() + "%");

            if (Comp.WorkStartHour.HasValue && Comp.WorkEndHour.HasValue)
            {
                HourFrom.InnerText = Comp.WorkStartHour.Value.ToString() + " სთ. - დან";
                HourTo.InnerText = Comp.WorkEndHour.Value.ToString() + " სთ. - მდე";
            }
            PriceFrom.Text = Comp.PriceFrom.HasValue ? Comp.PriceFrom.Value.ToString() : " - ";
            PriceTo.Text = Comp.PriceTo.HasValue ? Comp.PriceTo.Value.ToString() : " - ";
            PriceTo.Text += Comp.GEL == true ? " GEL" : "";
            PriceTo.Text += Comp.USD == true ? " USD" : "";
            PriceTo.Text += Comp.EUR == true ? " EUR" : "";

            IsWiFi.Text = Comp.WiFi == true ? " დიახ" : " ";
            AcceptCreditCard.Text = " დიახ";
            CompanyLogo.Src = "upload/" + (String.IsNullOrEmpty(Comp.Logo) ? "no-company-logo.jpg" : Comp.Logo);
            images = "http://revio.ge/" + CompanyLogo.Src;

            if (!IsPostBack)
            {
                map_div.InnerHtml = Comp.Map;
            }

            #region Create Gallery for the current company
            if (Comp.Gallery != null && Comp.Gallery.GalleryFiles != null && Comp.Gallery.GalleryFiles.Count != 0)
            {
                int i = 0;
                CompanyGallery.Text = "";
                foreach (var item in Comp.Gallery.GalleryFiles)
                {
                    var filepath = String.IsNullOrEmpty(item.File.FilePath) ? "no-company-gallery-image.jpg" : item.File.FilePath;
                    if (i == 0)
                    {
                        CompanyGallery.Text +=
                            "<div class=\"min_slide\">" +
                                "<div class=\"big_img\">" +
                                    "<a href=\"upload/" + filepath + "\" rel=\"imagegallery\">" +
                                        "<img src=\"upload/" + filepath + "\" width=\"94\" height=\"68\"/>" +
                                     "</a>" +
                                "</div>";
                    }
                    else
                    {
                        if (i < 4)
                        {
                            if (i == 3)
                            {
                                CompanyGallery.Text += "<div class=\"small_img_one\"><a href=\"upload/" + filepath + "\" rel=\"imagegallery\">" +
                                "<img src=\"upload/" + filepath + "\" width=\"25\" height=\"17\" /></a></div>";
                            }
                            else
                            {
                                CompanyGallery.Text += "<div class=\"small_img\"><a href=\"upload/" + filepath + "\" rel=\"imagegallery\">" +
                                "<img src=\"upload/" + filepath + "\" width=\"25\" height=\"17\" /></a></div>";
                            }
                        }
                        else
                        {
                            CompanyGallery.Text += "<a style=\"display:none;\" href=\"upload/" + filepath + "\" rel=\"imagegallery\">" +
                                "<img src=\"upload/" + filepath + "\" width=\"25\" height=\"17\" /></a>";
                        }
                    }
                    i++;
                }
                CompanyGallery.Text += "<div class='clear'></div><a class='add_photo' id=\"popup\" rel=\"pop\" href=\"PhotoUploaderPopUp.aspx?id=" + CompanyID + "\">დაამატე ფოტო</a></div>";
            }
            else
            {
                CompanyGallery.Text = "<div class=\"min_slide\">" +
                                       "<div class=\"big_img\">" +
                                           "<a href=\"#\"><img src=\"#\" width=\"94\" height=\"68\" alt=\"\"></a>" +
                                       "</div>" +
                                       "<div class=\"small_img\"><a href=\"#\"><img src=\"#\" width=\"25\" height=\"17\" alt=\"\"></a></div>" +
                                       "<div class=\"small_img\"><a href=\"#\"><img src=\"#\" width=\"25\" height=\"17\" alt=\"\"></a></div>" +
                                       "<div class=\"small_img_one\"><a href=\"#\"><img src=\"#\" width=\"25\" height=\"17\" alt=\"\"></a></div>" +
                                       "<div class=\"clear\"></div>" +
                                   "<a class='add_photo' id=\"popup\" rel=\"pop\" href=\"PhotoUploaderPopUp.aspx?id=" + CompanyID + "\">დაამატე ფოტო</a></div>";
            }
            #endregion


            if (Session["UserID"] != null)
            {
                AddReviewPlace.Visible = true;
                UserID = (int)Session["UserID"];
                Session["IsAllowWriteRev"] = checkBeforeWriteReview(UserID, CompanyID);
                if (UserID == Comp.UserID)
                {
                    EditCompany.HRef = "editcompany.aspx?id=" + CompanyID;
                }
                var UserObj = Master.GetAuthedUserObject();
                if (UserObj == null || UserObj.UserType != 0)
                {
                    DeleteReviewAdmin = "";
                }
            }
            else
            {
                AddReviewPlace.Visible = false;
                DeleteReviewAdmin = "";
                mainn.Visible = false;
            }

            if (Comp.UserID.HasValue)
            {
                CompanyCreator.Visible = true;
                EditCompany.Visible = false;
                CompanyOwner.InnerText = Comp.User.FirstName + " " + Comp.User.LastName;
                CompanyOwner.HRef = "userprofile.aspx?id=" + Comp.UserID;
                if (Comp.User.FaceID.HasValue)
                {
                    CompanyOwnerAvatar.Src = String.Format("http://graph.facebook.com/{0}/picture?width=50&height=50", Comp.User.FaceID.ToString());
                }
                else
                {
                    CompanyOwnerAvatar.Src = String.IsNullOrEmpty(Comp.User.Avatar) ? "images/no-avatar.jpeg" : "upload/" + Comp.User.Avatar;
                }
            }
            else
            {
                CompanyCreator.Visible = false;
            }

            if (Comp.Verified.HasValue && Comp.Verified.Value)
            {
                EditCompany.Visible = false;
                IsVerifiedInfo.Visible = true;
            }
            else
            {
                EditCompany.Visible = Session["UserID"] != null;
                EditCompany.HRef = "editcompany.aspx?id=" + CompanyID;
                IsVerifiedInfo.Visible = false;
            }



            BindRepeater();


            #region set company related companies...
            if (!IsPostBack)
            {
                foreach (var relComp in ma.GetRelatedCompanies(Comp.CompanyID).Take(5))
                {
                    var rlogo = String.IsNullOrEmpty(relComp.Logo) ? "no-company-logo.jpg" : relComp.Logo;
                    LitRelatedComp.Text +=
                        "<div class=\"comp_box\">" +
                           "<div class=\"comp_logo\">" +
                               "<img src=\"upload/" + rlogo + "\" width=\"69\" height=\"35\" />" +
                           "</div>" +
                           "<h3><a href=\"singlecompany.aspx?id=" + relComp.CompanyID + "\">" + relComp.Name + "</a></h3>" +
                           "<div style=\"float:left;\"><div class=\"outer-star\">" +
                           "<div style=\"position: relative; float: left;width:" + ((int)((relComp.Rating ?? 0) * 20)).ToString() + "%\" class=\"inner-star\">" +
                            "</div></div></div> &nbsp;&nbsp;&nbsp;" + (relComp.ReviewsCount ?? 0).ToString() + " განხილვა<br />" +
                           "<span>" + relComp.website + "</span>" +
                        "</div>";
                }
            }
            #endregion


            #region callback scripts
            ClientScriptManager cm = Page.ClientScript;
            String cbReference = cm.GetCallbackEventReference(this, "arg", "ReceiveServerData", "");
            String callbackScript = "function CallServer(arg, context) {" + cbReference + "; }";
            cm.RegisterClientScriptBlock(this.GetType(), "CallServer", callbackScript, true);
            #endregion

            Page.ClientScript
                .RegisterStartupScript(
                GetType(),
                "OnLoad",
                String.Format("initCompany('{0}','{1}','{2}','{3}','{4}')", id, title, descr, url, images),
                true);
        }
        else
        {
            Response.Redirect("default.aspx");
        }
    }

    public bool checkBeforeWriteReview(int UserID, int CompanyID)
    {
        ModelAdapter service = new ModelAdapter();
        Review rev = service.GetLastReviewByUserAndCompanyID(UserID, CompanyID);
        if (rev == null || rev.CreateDate.Value.Date != DateTime.Now.Date)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    protected void ReviewItemsRep_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        var item = (Review)e.Item.DataItem;
        string isLikedIt = "";
        string isDislikedIt = "";

        if (item != null)
        {
            if (UserID != null)
            {
                var userReview = item.UserReviews.FirstOrDefault(u => u.UserID == UserID && u.ReviewID == item.ReviewID);
                if (userReview != null)
                {
                    isLikedIt = userReview.IsLIke == true ? "images/like_icon.png" : "images/lke_grey.png";
                    isDislikedIt = userReview.IsDislike == true ? "images/dislike_icon.png" : "images/dislike_grey.png";
                }
            }
            var lit = (Literal)e.Item.FindControl("LitReviewItem");
            var crdate = (item.CreateDate ?? DateTime.Now.AddDays(-20));
            var subs = (DateTime.Now - crdate);
            var timeAgoString = subs.TotalMinutes < 60 ? subs.Minutes + " წუთის წინ..." : crdate.ToShortDateString();

            var avatar = "";
            if (item.User.FaceID.HasValue)
            {
                avatar = String.Format("http://graph.facebook.com/{0}/picture?width=50&height=50", item.User.FaceID.ToString());
            }
            else
            {
                avatar = string.IsNullOrEmpty(item.User.Avatar) ? "images/no-avatar.jpeg" : "upload/" + item.User.Avatar;
            }

            var upOrDown = ((item.Likes ?? 0) - (item.DisLikes ?? 0));
            var curs = upOrDown > 0 ? "+" + upOrDown.ToString() : upOrDown.ToString();

            string reviewImagesHtml = "";
            if (item.Gallery != null && item.Gallery.GalleryFiles != null && item.Gallery.GalleryFiles.Count > 0)
            {
                foreach (var imgItem in item.Gallery.GalleryFiles)
                {
                    reviewImagesHtml += "<div class=\"comp_commnt_img\">" +
                                            "<img width=\"172\" height=\"92\" src=\"upload/" + imgItem.File.FilePath + "\">" +
                                        "</div>";
                }
                reviewImagesHtml += "<div class=\"clear\"></div><br/>";
            }


            string like = "<a class=\"float\" name=\"like\" lik=\"" + item.ReviewID + "\" href=\"#\"><img width=\"17\" height=\"16\" src=\"images/lke_grey.png\"></a>";
            string dislike = "<a class=\"float\" name=\"dislike\" dislik=\"" + item.ReviewID + "\" href=\"#\"><img width=\"17\" height=\"16\" src=\"images/dislike_grey.png\"></a>";
            if (UserID == 0 || item.UserID == UserID)
            {
                like = "<a class=\"float\"  href=\"javascript:void\"><img width=\"17\" height=\"16\" src=\"images/lke_grey.png\"></a>";
                dislike = "<a class=\"float\" href=\"javascript:void\"><img width=\"17\" height=\"16\" src=\"images/dislike_grey.png\"></a>";

                //TODO კარგი იქნება თუ ვეტყვით რომ საუთარი მოწონება არ შეიძლება.
            }
            if (isLikedIt != "" && isDislikedIt != "")
            {
                like = "<a class=\"float\"  href=\"javascript:void\"><img width=\"17\" height=\"16\" src=\"" + isLikedIt + "\"></a>";
                dislike = "<a class=\"float\" href=\"javascript:void\"><img width=\"17\" height=\"16\" src=\"" + isDislikedIt + "\"></a>";
            }
            string isStar = "";
            if (item.Rating != null && item.Rating != 0)
            {
                var rat = (item.Rating ?? 0) * 20;
                isStar = "<div class=\"user_rat\"><div class=\"outer-star\">" +
                           "<div class=\"inner-star\" style=\"width: " + rat + "%; margin-left: 1px;\">" +
                           "</div></div></div>";
            }


            lit.Text = "<div class=\"clear\"> </div>" +
                        "<div class=\"mind_line\"> </div>" +
                        "<div style=\"float:left;\"><a href=\"userprofile.aspx?id=" + item.UserID + "\"><img width=\"65\" height=\"60\" src=\"" + avatar + "\"></a></div>" +
                        "<div id=\"" + item.CompanyID + "\" class=\"coment_review_three\">" +
                           "<h4><a href=\"userprofile.aspx?id=" + item.UserID + "\">" + item.User.FirstName + " " + item.User.LastName + "</a>" + isStar + "</h4>" + item.Review1 +
                           "<div class=\"clear\"> </div><br>" + reviewImagesHtml +
                           "<div class=\"like_cont\">" + like + dislike + "<span class=\"plus\">" + curs + "</span>" +
                           "</div>" +
                           "<div class=\"minutes_ago\">" +
                               "<span revid=\"" + item.ReviewID + "\" class=\"min_del\"> " + timeAgoString + "</span>" +
                               DeleteReviewAdmin +
                           "</div>" +
                           "<div class=\"minutes_ago\">" +
                                "<a name='review-share' style='text-decoration: none;' type='icon_link'" +
                                  "href='javascript: void(0)'>" +
                                  "<img src='images/fbshare.jpg' alt='Share' />" +
                                "</a>" +
                           "</div>" +
                        "</div>";
        }
    }

    protected void OnSubmit(object sender, EventArgs e)
    {
        try
        {
            if (Session["IsAllowWriteRev"] == null || !(bool)Session["IsAllowWriteRev"])
                return;
            if (ReviewText.Value.Length < 30)
                return;

            List<string> images = new List<string>();
            // Get the HttpFileCollection
            HttpFileCollection hfc = Request.Files;
            for (int i = 0; i < hfc.Count; i++)
            {
                HttpPostedFile hpf = hfc[i];

                if (hpf.ContentLength > 0)
                {
                    if (new String[] { ".png", ".jpg", ".gif", ".jpeg" }.Contains(System.IO.Path.GetExtension(hpf.FileName)))
                    {
                        string img = Guid.NewGuid().ToString().Substring(0, 10) +
                          System.IO.Path.GetFileName(hpf.FileName);
                        images.Add(img);
                        hpf.SaveAs(Server.MapPath("upload") + "\\" + img);
                    }
                }
            }
            ModelAdapter ma = new ModelAdapter();
            ma.ReviewAction(null, ReviewText.Value, int.Parse(HidnField.Value), CompanyID, UserID, images);
            if (Session["access_token"] != null)
            {
                #region write on fb
                //string msg1 = ReviewText.Value.Length > 30 ? ReviewText.Value.Substring(0, 30) : ReviewText.Value;
                //string msg = ReviewText.Value + " შეაფასე და მოიგე Kindle Fire და iPod Touch 5th Gen!";//Comp.Name + " - ჩემი შეფასება: " + ReviewText.Value + ".  შენ რას ფიქრობ?";
                //string fbPhoto = "";
                //if (!String.IsNullOrEmpty(Comp.Logo))
                //{
                //    fbPhoto = "http://revio.ge/upload/" + Comp.Logo;
                //}
                //Facebook.WriteOnFace(msg,
                //    Session["access_token"].ToString(),
                //    fbPhoto,
                //    "http://revio.ge/singlecompany.aspx?id=" + Comp.CompanyID); 
                #endregion
            }
            Response.Redirect(Request.Url.OriginalString, false);
        }
        catch (Exception ex)
        {
            Script.Text = "<script>alert('დაფიქსირდა შეცდომა'); window.location = 'singlecompany.aspx?id=" + CompanyID + "';</script>";
            //TODO Log exception!
        }
    }

    protected void lb_Click(object sender, EventArgs e)
    {
        var lb = (LinkButton)sender;
        if (lb.Text == "ბოლო")
        {
            CurrentPage = 10000;
        }
        else if (lb.Text == "►")
        {
            CurrentPage += 1;
        }
        else
        {
            CurrentPage = int.Parse(lb.Text) - 1;
        }
        BindRepeater();
    }

    private void BindRepeater()
    {
        var service = new ModelAdapter();
        var coll = service.GetReviewsByCompanyID(CompanyID).OrderByDescending(c => c.ReviewID).ToList();
        ItemCount = coll.Count;

        PagedDataSource Pds1 = new PagedDataSource();
        Pds1.DataSource = coll;
        Pds1.AllowPaging = true;
        Pds1.PageSize = PageSize;
        ReviewItemsRep.DataSource = Pds1;



        var lastIndex = PagesCount = ItemCount % PageSize == 0 ? (ItemCount / PageSize) : (ItemCount / PageSize) + 1;
        var startIndex = 1;

        if (lastIndex - startIndex > 0)
        {
            Pds1.CurrentPageIndex = CurrentPage;
            pages.Controls.Clear();
            for (int i = startIndex; i <= lastIndex; i++)
            {
                var lb = new LinkButton() { Text = i.ToString(), CssClass = "page_bg_num" };
                lb.ID = "btnlink" + i.ToString();
                lb.CssClass = "page_bg_num";
                lb.Click += new EventHandler(lb_Click);
                pages.Controls.Add(lb);
            }
            if (CurrentPage != lastIndex - 1)
            {
                // show next
                var lb1 = new LinkButton() { Text = "►", CssClass = "page_bg_num" };
                lb1.ID = "btnlink-1";
                lb1.Click += new EventHandler(lb_Click);
                pages.Controls.Add(lb1);

                // show last
                var lblast = new LinkButton() { Text = "ბოლო", CssClass = "page_bg_num" };
                lblast.ID = "lblast100";
                lblast.CssClass = "page_last";
                lblast.Click += new EventHandler(lb_Click);
                pages.Controls.Add(lblast);
            }
        }
        ReviewItemsRep.DataBind();
    }

    string ICallbackEventHandler.GetCallbackResult()
    {
        return callBackData;
    }

    void ICallbackEventHandler.RaiseCallbackEvent(string eventArgument)
    {
        try
        {
            var parts = eventArgument.Split('|');
            if (String.IsNullOrEmpty(eventArgument))
            {
                callBackData = "Error|დაფიქსირდა შეცდომა";
                return;
            }
            callBackData = "Success|";


            switch (parts[0])
            {
                case "RemoveReview":
                    {
                        var RevID = int.Parse(parts[1]);
                        callBackData += "RemoveReview|" + ma.ReviewDelete(RevID);
                        break;
                    }
                case "Like":
                    {
                        var RevID = int.Parse(parts[1]);
                        callBackData += "Like|" + ma.ReviewLike(RevID, UserID);
                        break;
                    }
                case "DisLike":
                    {
                        var RevID = int.Parse(parts[1]);
                        callBackData += "DisLike|" + ma.ReviewDisLike(RevID, UserID);
                        break;
                    }
                default:
                    {
                        break;
                    }
            }
        }
        catch (Exception ex)
        {
            callBackData = "Error|დაფიქსირდა შეცდომა";
            return;
        }
    }
}
